﻿using System;
using System.Collections.Generic;
using System.Linq;
using ZilLion.Service.Core.Ioc;
using ZilLion.Service.Core.WebSocket.Interface;

namespace ZilLion.Service.Core.WebSocket
{
    public class MessageHandleStrategyFactory
    {
        private static volatile MessageHandleStrategyFactory _instance;
        private static readonly object Lock = new object();

        private static readonly List<Type> _strategyTypes = new List<Type>();

        private MessageHandleStrategyFactory()
        {
        }

        /// <summary>
        ///     管理中控的host
        /// </summary>
        public string ManagerServiceHost { get; private set; }

        public static MessageHandleStrategyFactory GetInstance()
        {
            if (_instance == null)
                lock (Lock)
                {
                    if (_instance == null)
                        _instance = new MessageHandleStrategyFactory();
                    foreach (var componentLoader in IocConfig.ComponentLoaderCache)
                        _strategyTypes.AddRange(componentLoader.Value.WebSocketHandlStrategyTypes);
                }
            return _instance;
        }

        public IMessageHandleStrategy GetStrategyInstance(string messageType)
        {
            var strategytype = _strategyTypes.FirstOrDefault(x =>
                string.Equals(x.Name.ToLower().Replace("messagehandlestrategy", string.Empty), messageType,
                    StringComparison.CurrentCultureIgnoreCase));
            if (strategytype == null) return null;
            var instance = IocContainer.Resolve(strategytype);
            return instance as IMessageHandleStrategy;
        }
    }
}